using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ERP.RBAC
{
    public class PermissionServices : ApplicationService, IPermissionServices
    {
        private readonly IRepository<Permissions, int> _permissionsRepository;
        private readonly IRepository<RolePermission, int> _rolePermissionRepository;

        public PermissionServices(
            IRepository<Permissions, int> permissionsRepository,
            IRepository<RolePermission, int> rolePermissionRepository)
        {
            _permissionsRepository = permissionsRepository;
            _rolePermissionRepository = rolePermissionRepository;
        }

        /// <summary>
        /// 获取所有权限列表
        /// </summary>
        /// <returns>权限列表</returns>
        public async Task<List<Permissions>> GetAllPermissionsAsync()
        {
            return await _permissionsRepository.GetListAsync();
        }

        /// <summary>
        /// 获取角色的权限ID列表
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns>权限ID列表</returns>
        public async Task<List<int>> GetRolePermissionsAsync(int roleId)
        {
            var rolePermissions = await _rolePermissionRepository.GetListAsync(rp => rp.RoleId == roleId);
            return rolePermissions.Select(rp => rp.PermissionId).ToList();
        }

        /// <summary>
        /// 保存角色权限
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="permissionIds">权限ID列表</param>
        /// <returns>是否成功</returns>
        public async Task<bool> SaveRolePermissionsAsync(int roleId, List<int> permissionIds)
        {
            try
            {
                // 删除该角色的所有现有权限
                await _rolePermissionRepository.DeleteAsync(rp => rp.RoleId == roleId);

                // 添加新的权限
                foreach (var permissionId in permissionIds)
                {
                    await _rolePermissionRepository.InsertAsync(new RolePermission
                    {
                        RoleId = roleId,
                        PermissionId = permissionId
                    });
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
} 